import 'dart:io';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/play_audio.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/pages/xspace/detail/xcomment_voice.dart';
import 'package:flutter/material.dart';
import 'package:gesture_zoom_box/gesture_zoom_box.dart';

class XPostEditImgPage extends StatefulWidget {

  final List<File> list;
  final Function(int index) onDelete;
  final List<Map> imgVoice;
  final Function(List<Map> val) onEditFinish;
  final String heroTag;

  const XPostEditImgPage({
    Key key, 
    this.list, 
    this.onDelete, 
    this.onEditFinish,
    this.imgVoice,
    this.heroTag,
  }) : super(key: key);

  @override
  _XPostEditImgPageState createState() => _XPostEditImgPageState();
}

class _XPostEditImgPageState extends State<XPostEditImgPage> {

  List<File> _list = [];
  int idx = 0;
  int itemCount = 0;
  // 音频数据
  List<Map> sources = [];
  PageController _pageController;

  int audioTime = 0;
  bool isplay = false;

  @override
  void initState() {
    super.initState();

    int initIndex = 0;
    if(widget.heroTag != null) initIndex = int.parse(widget.heroTag.substring(widget.heroTag.length - 1));
    idx = initIndex;
    _pageController = PageController(initialPage: initIndex);

    if(widget.list != null){
      // 对象，有隐式操作，会造成bug
      widget.list.forEach((element) { 
        _list.add(element);
        final tempIndex = widget.list.indexOf(element); // 给图片添加语音，如果没有对应的语音就添加一个空的字典
        if(widget.imgVoice != null && tempIndex < widget.imgVoice.length){
          sources.add(widget.imgVoice[tempIndex]);
          if(tempIndex == initIndex) {
            setState(() { // 如果录音文件在第一张图，设置显示语音的时间
              audioTime = widget.imgVoice[idx]["duration"];
            });
          }
        } else {
          sources.add({});
        }
      });
      setState(() {
        itemCount = _list.length;
      });
    }
  }

  @override
  void dispose(){
    _pageController.dispose();
    super.dispose();
  }

  Widget _recordOrplay() {
    Map audio = sources[idx];
    if(audio.isNotEmpty) {
      final size = MediaQuery.of(context).size;
      return GestureDetector(
        onTap: (){
          // MyNetWorkPlayer.instance.play(sender:audio["path"], islocal: true, audioduration: audio["duration"], onPlayDuration: (second){
          //   setState(() {
          //     audioTime = second;
          //     isplay = audio["duration"] != second;
          //   });
          // });
          AlertTool.showVoiceBottomDialog(context,
            duration: audio["duration"], 
            path: audio["path"],
            onFinish: (path, duration){
              if(path == null) return;
              setState(() {
                audioTime = duration;
                sources[idx] = {"path":path, "duration":duration};
              });
            }
          );
        },
        child: FlrTestPlatWidget(
                        width: size.width * 0.4,
                        padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 10),
                        isplay: isplay, duration: audioTime
                      ),
      );
    } else {
      return GestureDetector(
        onTap: (){
          AlertTool.showVoiceBottomDialog(context,
            onFinish: (path, duration){
              if(path == null) return;
              setState(() {
                audioTime = duration;
                sources[idx] = {"path":path, "duration":duration};
              });
            }
          );
        },
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 8),
          decoration: BoxDecoration(
            color: APP_main_color,
            borderRadius: BorderRadius.circular(20)
          ),
          child: Row(
            children: [
              Image.asset("assets/yy22.png", color: Colors.white,),
              SizedBox(width: 5,),
              Text("语音录制", style: instanceTextStyle(15, Colors.white),)
            ],
          ),
        ),
      );
    }
  }

  _deleImage() {
    AlertTool.showConfirmDialog(
        context, 
        title: "确定要删除这张照片", 
        sureCallback: (){
          if(widget.onDelete != null) widget.onDelete(idx); // 回调删除
          _list.removeAt(idx);
          // 删除图片对应的音频
          _deleAudio();

          if(_list.length == 0) {
            Navigator.of(context).pop();
            return;
          }
          setState(() {
            idx = _list.length - 1;
            itemCount = _list.length;
            Map audio = sources[idx];
            if(audio.keys.length != 0) audioTime = audio["duration"];
          });
    });
  }

  _deleAudio() async {
    Map audio = sources.removeAt(idx);
    if(audio.isNotEmpty) await File(audio["path"]).delete();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        centerTitle: true,
        title: Text("${idx + 1}/${_list.length}", style: instanceTextStyle(17, Colors.white),),
        leading: IconButton(
          icon: Image.asset("assets/fanhui1.png"),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            icon: Image.asset("assets/lajit.png", color: Colors.white,),
            onPressed: _deleImage
          )
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: PageView.builder(
                scrollDirection: Axis.horizontal,
                controller: _pageController,
                itemCount: itemCount,
                onPageChanged: (index){
                  if(sources[index] != null) {
                    Map audio = sources[index];
                    setState(() {
                      audioTime = audio["duration"];
                    });
                  }
                  // 停止上个图片的音频播放
                  setState(() {
                    idx = index;
                  });
                },
                itemBuilder: (context, index) {
                  return GestureZoomBox(
                      maxScale: 5.0,
                      doubleTapScale: 2.0,
                      duration: Duration(milliseconds: 200),
                      child: Hero(
                        tag: widget.heroTag,
                        child: Image.file(_list[index], fit: BoxFit.fitWidth,)
                      )
                  );
                }
              ),
            ),
            Container(
              padding: const EdgeInsets.only(left: 10, right: 10, bottom: 24),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("编辑",style: instanceTextStyle(15, Colors.white)),
                  _recordOrplay(),
                  GestureDetector(
                    onTap: (){
                      if(widget.onEditFinish != null) widget.onEditFinish(sources);
                      Navigator.of(context).pop();
                    },
                    child: Text("确认",style: instanceTextStyle(15, Colors.white))
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}